package com.gitee.zhangchenyan.takin.auth;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gitee.zhangchenyan.takin.cache.IJedisClient;
import com.gitee.zhangchenyan.takin.common.utils.HttpServletUtils;

import javax.security.auth.message.AuthException;
import java.time.LocalDateTime;

/**
 * @Deacription TODO
 * @Author Administrator
 * @Date 2021/12/8 22:01
 * @Version 1.0
 **/
@Component
public class AuthUserServiceImpl implements AuthUserService {

    protected static final String REDIS_TOKEN_KEY = "takin_token_";
    public static final String NOT_LOGIN_MSG = "登录过期";
    @Autowired
    private IJedisClient jedisClient;

    @Override
    public AuthUserIdentity login(Object user) {
        return login(user, 3600 * 2L);
    }

    @Override
    public AuthUserIdentity login(Object user, Long seconds) {
        String token = RandomUtil.randomString(128);
        LocalDateTime absoluteExpirationTime = LocalDateTime.now().plusSeconds(seconds);
        jedisClient.set(REDIS_TOKEN_KEY + token, seconds, JSON.toJSONString(user));
        HttpServletUtils.setCookie("token", token, Convert.toInt(seconds));
        return new AuthUserIdentity("token", token, absoluteExpirationTime);
    }

    @Override
    public void logout() {
        String token = getToken();
        HttpServletUtils.deleteCookie("token");
        jedisClient.del(REDIS_TOKEN_KEY + token);
    }

    @Override
    public String getToken() {
        Object token = HttpServletUtils.GetHttpServletRequest().getAttribute("token");
        if (token == null)
            return null;
        return token.toString();
    }

    @SneakyThrows
    @Override
    public <A> A getUser(Class<A> clazz) {
        String token = getToken();
        if (token == null)
            return null;
        String user = jedisClient.get(REDIS_TOKEN_KEY + token);
        if (StrUtil.isEmpty(user))
            throw new AuthException(NOT_LOGIN_MSG);
        return JSON.parseObject(user, clazz);
    }

    @Override
    @SneakyThrows
    public Long getId() {
        String token = getToken();
        if (token == null)
            return null;
        String user = jedisClient.get(REDIS_TOKEN_KEY + token);
        if (StrUtil.isEmpty(user))
            throw new AuthException(NOT_LOGIN_MSG);
        return JSON.parseObject(user).getLong("id");
    }
}
